<?php
namespace Home\Model;

use  Think\Model;

class CartsModel extends Model
{
  protected $autoCheckFields =false;

  public function get_cart($user_id)
  {
    $message = array("code"=>0,"msg"=>array(),"data"=>array());
    $DB_PREFIX = C("DB_PREFIX");

    $where['user_id'] = $user_id;
    $cart_id = M("carts")->where($where)->getField("id");
    if (!$cart_id) {
      return false;
    }

    //商品状态--商品ID---商品数量--商品价格
    $where = " cp.cart_id=".$cart_id;
    $order = "cp.id desc ";
    $field = "cp.id,cp.product_id,cp.num as product_num,p.name as product_name,p.status,(s.price+p.price) as product_price,s.name as product_spec,cp.spec_id,p.stock ";
    $list = M("cart_products")->alias("cp")->join("left join ".$DB_PREFIX."products p  on p.id=cp.product_id")
                        ->join("left join ".$DB_PREFIX."specs s on s.id=cp.spec_id")
                        ->field($field)->where($where)->order($order)->select();

    $cart_order = array();
    $cart_order['list'] = $list;
    $total_amount = 0;
    $error=array();
    foreach ($list as $key => $value) {
      $total_amount = $value['product_price'] * $value['product_num'] + $total_amount;
      //库存不足报错
      if ($value['product_num']>$value['stock']) {
        $message['code']=10001;
        $len = count($message['msg']);
        $message['msg'][$len]['cart_id']=$value['id'];
        $message['msg'][$len]['product_id']=$value['product_id'];
        // $message['data'][$len]['spec_id']=$value['spec_id'];
      }
    }

    $cart_order['total_amount'] = $total_amount;
    $cart_order['cart_id'] = $cart_id;

    $message['data']=$cart_order;

    return $message;
  }
}
